在ios7之前,要掃描QR code必須要用到第三方程式,但現在ios已經內建這項功能。
這次我們要用到 “AVCaptureSession” 這個類別並且偵測裝置中的相機
在 < info.plist > 中建立相機、相簿的使用權限
建立一個新的類別: “DeviceInput”,並且繼承 “NSObject”
在 < DeviceInput.swift >
匯入 “AVFoundation”
import AVFoundation
宣告 input 相關輸入方式
class DeviceInput: NSObject {
//declared the input device
var frontWildAngleCamera : AVCaptureDeviceInput? //frontwildAngleCamera
var backWildAngleCamera: AVCaptureDeviceInput? // backwildAngleCamera
var backTelephotoCamera: AVCaptureDeviceInput? //backtelephotoCamera
var backDualCamera: AVCaptureDeviceInput? // dual camera
//get all the camera type
func getAllCameras() {
let cameraDevices = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera, .builtInTelephotoCamera, .builtInDualCamera],mediaType: .video, position: .unspecified).devices
for camera in cameraDevices {
let inputDevice = try! AVCaptureDeviceInput(device: camera)
if camera.deviceType == .builtInWideAngleCamera, camera.position == .front {
frontWildAngleCamera = inputDevice
}
if camera.deviceType == .builtInWideAngleCamera, camera.position == .back {
backWildAngleCamera = inputDevice
}
if camera.deviceType == .builtInTelephotoCamera {
backTelephotoCamera = inputDevice
}
if camera.deviceType == .builtInDualCamera {
backDualCamera = inputDevice
}
}
}
override init() {
super.init()
getAllCameras()
}